package com.xiangyang.utils;

import com.xiangyang.entity.vo.CaptchaImage;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

public class ImageCaptchaGenerator {

    private static final Random RANDOM = new Random();
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    /**
     * 生成指定长度的字符验证码
     *
     * @param length 验证码长度
     * @return 生成的验证码
     */
    private String generateRandomString(int length) {
        StringBuilder captcha = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int randomIndex = RANDOM.nextInt(CHARACTERS.length());
            captcha.append(CHARACTERS.charAt(randomIndex));
        }
        return captcha.toString();
    }

    /**
     * 生成图片验证码
     *
     * @param width  图片宽度
     * @param height 图片高度
     * @param length 验证码长度
     * @return 生成的验证码和图片字节数组
     * @throws IOException 如果生成图片时发生错误
     */
    public CaptchaImage generateCaptchaImage(int width, int height, int length) throws IOException {
        String captchaText = generateRandomString(length);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();

        // 设置背景色
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);

        // 设置字体
        Font font = new Font("Arial", Font.BOLD, 24);
        g2d.setFont(font);

        // 设置文本颜色
        g2d.setColor(Color.BLACK);

        // 绘制验证码文本
        for (int i = 0; i < length; i++) {
            char c = captchaText.charAt(i);
            int x = i * (width / length) + (width / length) / 2;
            int y = height / 2 + 10;
            g2d.drawChars(new char[]{c}, 0, 1, x, y);
        }

        // 添加干扰线
        g2d.setStroke(new BasicStroke(2));
        for (int i = 0; i < 5; i++) {
            int x1 = RANDOM.nextInt(width);
            int y1 = RANDOM.nextInt(height);
            int x2 = RANDOM.nextInt(width);
            int y2 = RANDOM.nextInt(height);
            g2d.drawLine(x1, y1, x2, y2);
        }

        // 将图片转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        byte[] imageBytes = baos.toByteArray();

        g2d.dispose();

        return new CaptchaImage(captchaText, imageBytes);
    }

    public static void main(String[] args) {
        ImageCaptchaGenerator generator = new ImageCaptchaGenerator();
        try {
            CaptchaImage captchaImage = generator.generateCaptchaImage(120, 40, 6);
            System.out.println("Generated Captcha Text: " + captchaImage.getCaptchaText());
            // 你可以将 imageBytes 发送到客户端或保存到文件
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

